package com.binarysorttree;

import java.util.HashMap;
import java.util.Map;

public class Node {
    int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    /**
     * 添加结点：以递归的形式添加结点，满足二叉排序树的特点
     */
    public void add(Node node){
        if(node == null){
            return;
        }
        if(node.value < this.value){
            if(this.left != null){
                this.left.add(node);
            }else {
                this.left = node;
            }
        }else {
            if(this.right != null){
                this.right.add(node);
            }else {
                this.right = node;
            }
        }
    }
    /**
     * 中序遍历
     */
    public void infixOrder(){
        if(this.left != null){
            this.left.infixOrder();
        }
        System.out.println(this);
        if(this.right != null){
            this.right.infixOrder();
        }
    }
    /**
     * 根据value查找到对应的结点和父结点并保存在map中
     */
    public void search(int value, Map<String,Node> map){
        if(value == this.value){
            map.put("curNode",this);
            return ;
        }else if(value > this.value){
            if(this.right != null){
                map.put("parNode",this);
                this.right.search(value,map);
            }
        }else {
            if(this.left != null){
                map.put("parNode",this);
                this.left.search(value,map);
            }
        }
        //待查找的value不存在
       if(map.get("curNode") == null){
           map.clear();
       }
        return;
    }


}
